# Methods added to this helper will be available to all templates in the application.

require 'rexml/document'
include REXML

module ApplicationHelper

  def options_will_paginate(hash_options_param = {})
    
    hash_options =  { #:outer_window => 0,
                      #:inner_window => 0,                      
                      :previous_label => "&laquo; #{t('lbl_previous')}",
                      :next_label => "#{t('lbl_next')} &raquo;"}

    hash_options_param.each { |key,value| hash_options[key] = value }
    return hash_options
  end

  def show_page_access_denied
    flash[:error] = t('lbl_access_denied')
    redirect_to root_url
  end

  def save_redirect_back url
    session[:return_to] = url
  end

  def redirect_back_or_default path
    session[:return_to] ? redirect_to(session[:return_to]) : redirect_to(path)
    session[:return_to] = nil
  end

  def count_record_per_page(entity=nil)
    if entity.nil?
      return Setting.count_record_per_page_general
    else
      var = "count_record_per_page_#{entity}"
      value = Setting[var]
      if !value.nil?
        return value
      else
        return Setting.count_record_per_page_general
      end
    end
  end

  def flash_message(type, text)
      flash[type] ||= []
      flash[type] << text
  end

  def get_sex_hash
    @hash_sex ={t('lbl_female') => 'F', t('lbl_male') => 'M'}
  end

  def get_sex_description key
    if key == 'F'
      t('lbl_female')
    else
      t('lbl_male')
    end
  end

  def get_boolean_description value
    if value
      t('lbl_true')
    else
      t('lbl_false')
    end
  end

  def get_language_name value
    if value == "es"
      return t('lbl_language_spanish')
    end
    if value == "en"
      return t('lbl_language_english')
    end
  end

  def get_mail_format_label value
    if value == "text"
      return t('lbl_mail_format_text')
    end
    if value == "html"
      return t('lbl_mail_format_html')
    end
  end

  def get_sex_label value
    if value == "f"
      return t('lbl_sex_f')
    end
    if value == "m"
      return t('lbl_sex_m')
    end
  end

  def get_menu_user_to_xml

    user_signed_in = user_signed_in?
    menu_xml_str = ""

    file = File.new("config/menu.xml")
    doc = Document.new(file)
    doc.elements.each('Menu/Menu.menu_item'){ |menu_item|

      #se verifica si es necesario que el usuario este logueado
      load = user_signed_in || menu_item.attribute("user_signed_in").to_s == "N"
      #se borra el atributo para que no le joda al java script
      menu_item.delete_attribute("user_signed_in")

      #se verifica si el usuario tiene alguno de los roles del menu_item
      if load
        load = false
        if user_signed_in
          if menu_item.elements['roles'].text.nil?
            load = true
          else
            menu_item_roles = menu_item.elements['roles'].text.split(",")
            current_user.roles.each {|r| if menu_item_roles.include?(r) then load = true end }
          end
        else
          load = true
        end
      end

      #se verifica si se cumplen las condiciones
      if load
        if !menu_item.elements['conditions'].text.nil?
          menu_item_conditions = menu_item.elements['conditions'].text.split(",")
          menu_item_conditions.each {|c| if !eval(c) then load = false end }
        end
      end

      if load
        #se actualiza el valor correcto para el elemento "name" en funcion del atributo "i18n"
        if menu_item.elements['name'].attribute("i18n").to_s == 'S'
          menu_item.elements['name'].text = t(menu_item.elements['name'].text)
        end
        #se borra el atributo para que no le joda al java script
        menu_item.elements['name'].delete_attribute("i18n")

        #se actualiza el valor url en funcion del atributo "execute_code"
        if menu_item.elements['url'].attribute("execute_code").to_s == 'S'
          menu_item.elements['url'].text = eval(menu_item.elements['url'].text)
        end
        #se borra el atributo para que no le joda al java script
        menu_item.elements['url'].delete_attribute("execute_code")

        #armo el elemento "Menu.MenuItem>" como un string sin saltos de linea
        menu_xml_str += "<Menu.menu_item>#{menu_item.elements['id']}#{menu_item.elements['parent_id']}#{menu_item.elements['name']}#{menu_item.elements['url']}</Menu.menu_item>"
      end

    }
    menu_xml_str = "<Menu xmlns=\"Retta\">" + menu_xml_str +  "</Menu>"

    return menu_xml_str
  end

  def user_has_contact?
    return !Contact.find_by_user_id(current_user.id).nil?
  end

  def load_wish_list_current_user
    if !current_user.nil?
      wish_lists_special = WishList.find :all, :conditions => ["user_id = ? and type_list != ?", current_user.id, WishList::TYPE_SIMPLE], :order => "name"
      wish_lists_simple = WishList.find(:all, :conditions => ["user_id = ? and type_list = ?", current_user.id, WishList::TYPE_SIMPLE], :order => "name")
      @wish_lists = wish_lists_special + wish_lists_simple
    else
      @wish_lists = []
    end
  end

  def get_website_url language
    request_path = request.url.split(Setting.spanish_website_url)[1] unless request.url.index(Setting.spanish_website_url).nil?
    request_path = request.url.split(Setting.english_website_url)[1] unless request.url.index(Setting.english_website_url).nil?

    route = ''
    if language == 'es'
      route += Setting.spanish_website_url
    else
      route += Setting.english_website_url
    end

    route += request_path unless request_path.nil?
    route += '/index_without_clean' if !request_path.nil? && !request_path.index('catalogs').nil?

    return route
  end

end
